<template>
  <div class="course-video">
    <el-form label-width="80px" size="small" style="width:60%;margin:0 auto;">
      <el-form-item label="课程">
        <el-input v-model="courseName" disabled></el-input>
      </el-form-item>
      <el-form-item label="课时">
        <el-input v-model="themeName" disabled></el-input>
      </el-form-item>
       <el-form-item label="视频上传">
        <input ref="video-file" type="file"/>
      </el-form-item>
       <el-form-item label="选择封面">
        <input ref="image-file" type="file"/>
      </el-form-item>
      <el-button size="small" type="primary" @click="handleUpload">点击上传</el-button>
      <el-button size="small" @click="$router.push({
        name: 'sections',
        params:{ courseId }
      })">返回</el-button>
      <p v-if="uploadPercent !== 0">视频上传中: {{ uploadPercent }}%</p>
      <p v-if="isUploadSuccess">视频转码中: {{ isTransCodeSusscess ? "完成" : '未完成' }}</p>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable */
import bus from '@/assets/js/busEvent'
import {
  aliyunImgUploadAddressAndAuth,
  aliyunVideoUploadAddressAndAuth,
  aliyunTransCode,
  aliyunTransCodePercent,
} from '@/services/video'
export default {
  name: 'courseVideo',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    },
    lessonId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      courseName: '',
      themeName: '',
      // 保存上传实例
      uploader: null,
      // 存储图片地址,用于视频上传凭证请求
      imageUrl: '',
      // 视频Id
      videoId: '',
      // 视频上传进度
      uploadPercent: 0,
      // 视频转码是否成功
      isTransCodeSusscess: false,
      // 视频上传是否成功
      isUploadSuccess: false
    }
  },
  mounted () {
    this.courseName = bus.sendCourseName
    this.themeName = bus.theme
  },
  created () {
    this.initUploader()
  },
  methods: {
    handleUpload () {
      // 点击上传时重置状态信息
      this.isTransCodeSusscess = false
      this.isUploadSuccess = false
      this.uploadPercent = 0
      // 获取上传的文件
      const imageFile = this.$refs['image-file'].files[0]
      const videoFile = this.$refs['video-file'].files[0]
      // 将文件添加到上传列表
      const uploader = this.uploader
      uploader.addFile(imageFile)
      uploader.addFile(videoFile)
      // 开始上传
      // 开始上传后,上面的文件会按添加的顺序依次上传
      uploader.startUpload()
    },
    initUploader () {
      this.uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: "1618139964448548",
        // 上传到视频点播的地域, 默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        //  开始上传 (上传凭证处理)
        onUploadstarted: async uploadInfo => {
          this.isUploadSuccess = false
          // 一.获取凭证
          // 获取到当前上传的文件信息
          // console.log(uploadInfo)
          // 1.声明变量存储得到上传凭证
          let uploadAddressAndAuth = null
          // 2.根据 isImage 检测上传文件类型
          if (uploadInfo.isImage) {
            // 阿里云图片上传凭证接口
            const { data } = await aliyunImgUploadAddressAndAuth()
            if (data.code === '000000') {
              // 3.data.data 即为凭证信息组成的对象
              uploadAddressAndAuth = data.data
              // 4. 因为阿里云视频上传需要传递图片的 imageUrl
              this.imageUrl = uploadAddressAndAuth.imageURL
            }
          } else {
            // 5.根据 uploadInfo 数据, 根据请求参数名设置参数
            const { data } = await aliyunVideoUploadAddressAndAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageUrl
            })
            if (data.code === '000000') {
              // 6.存储凭证
              // 图片与视频上传的区别在于图片存在 imageId, 视频存在 videoId ,其他相同
              uploadAddressAndAuth = data.data
              this.videoId = uploadAddressAndAuth.videoId
            }
          }
          // 二. 设置凭证 (后台返回的数据)
          this.uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAddressAndAuth.uploadAuth,
            uploadAddressAndAuth.uploadAddress,
            uploadAddressAndAuth.imageId || uploadAddressAndAuth.videoId
          )
        },
        // 文件上传成功
        onUploadSuccee: function (uploadInfo) {
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
          if (!uploadInfo.isImage) {
           this.uploadPercent = Math.floor(loadedPercent*100)
          }
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
        },
        // 全部文件上传结束 (对视频进行转码请求)
        onUploadEnd: async uploadInfo => {
          this.isUploadSuccess = true
          const { data } = await aliyunTransCode({
            lessonId: this.lessonId,
            fileId: this.videoId,
            fileName: this.$refs['video-file'].files[0].name,
            coverImageUrl: this.imageUrl
          })
          if (data.code === '000000') {
            const timer = setInterval(async () => {
              const { data } = aliyunTransCodePercent(this.lessonId)
              if (data === 100 ) {
                this.isTransCodeSusscess = true
                clearInterval(timer)
                this.$message.success('转码成功')
              }
            },1000)
          }
        }       
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
